package cn.itcast.users.service.impl;

import cn.itcast.constant.JwtClaimsConstant;
import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.WeChatConstant;
import cn.itcast.exception.LoginFailedException;
import cn.itcast.properties.JwtProperties;
import cn.itcast.properties.WeChatProperties;
import cn.itcast.users.dto.UserLoginDTO;
import cn.itcast.users.mapper.UserMapper;
import cn.itcast.users.pojo.User;
import cn.itcast.users.service.UserService;
import cn.itcast.users.vo.UserLoginVO;
import cn.itcast.utils.HttpClientUtil;
import cn.itcast.utils.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * c端用户登录
     *
     * @param dto
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //拿到OpenId
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", dto.getCode());
        map.put("grant_type", "authorization_code");


        String s = HttpClientUtil.doGet(WeChatConstant.WX_LOGIN,
                map);
        String openid = JSONObject.parseObject(s).get("openid") + "";
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //如果数据库中没有此id则认证为新用户。
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insete(user);
        }

        //生成令牌，封装数据返回
        Map<String, Object> mapUser = new HashMap();
        mapUser.put(JwtClaimsConstant.USER_ID, user.getId());

        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                mapUser
        );

        return UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(jwt)
                .build();
    }

    /**
     * 根据id查询user
     *
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }
}
